package com.sofwin.configer;

import com.sofwin.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @packageName: com.sofwin.configer
 * @user: andyliu
 * @date: 2023/1/5 16:41
 * @email 115176513@qq.com
 * @description: TODO
 */
@Configuration
@Component
public class ShiroConfiger {

    @Autowired
    private MyRealm realm;
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager());
        bean.setLoginUrl("/index.jsp");
        // 配置过滤器链有2种方法，一种通过配置字符串来配置过滤器链
//        bean.setFilterChainDefinitions("/** anon");
        Map<String,String> definitionMap = new HashMap<>();
        definitionMap.put("/**","authc"); // 所有资源都需要登录后访问（静态资源）
        definitionMap.put("/static/**","anon");
        definitionMap.put("/login","anon");
        definitionMap.put("/verification","anon");
        bean.setFilterChainDefinitionMap(definitionMap);
        return bean;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");// 设置散列机密使用的算法 MD5 SHA
        matcher.setHashIterations(10); // hash算法的迭代次数 10次hash算法
        matcher.setHashSalted(true); // 设置是否使用盐值加密
        return matcher;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        manager.setRealm(realm);
        return manager;
    }
}
